# encoding: utf-8
import datetime
from flask_restplus import Resource
from app.extensions.api import Namespace
from app.modules.common.utils import DbCommit, db
from . import schemas, parameters
from .models import LogInfo
from app.modules.notify.notifier import send_message
from app.modules.notify.models import NotifyModel

api = Namespace('log', description = "执行日志")  # pylint: disable=invalid-name


@api.route('/')
class GetLog(Resource):
    @api.parameters(parameters.GetParameters())
    @api.response(schemas.LogListSchema(many = False))
    def get(self, args):
        """
        查询日志记录，只返回当前时间和前一天的
        :return:
        """
        _env_name = args['env_name']
        _zone_code = args['zone_code']

        now = datetime.datetime.now() - datetime.timedelta(days = 1)
        _date = datetime.datetime(now.year, now.month, now.day, 0, 0, 0)

        _list = LogInfo.query.filter_by(zone_code = _zone_code, env_name = _env_name).filter(
            LogInfo.create_time >= _date).order_by(LogInfo.create_time.asc()).all()

        return {'success': True, 'msg': '', 'data': _list}


def insertLog(log = None, account = None, br_count = 0, color = None, zone_code = None, env_name = None,
              entrance_types = None, group = None, show_error = '1'):
    _info = LogInfo(log = log, account = account, br_count = br_count, color = color, zone_code = zone_code,
                    env_name = env_name, entrance_types = entrance_types, group = group, show_error = show_error)
    db.session.add(_info)
    DbCommit()
    send_message(
        NotifyModel('%s_%s_log' % (env_name, zone_code), LogInfo.query.filter_by(id = _info.id).first().to_dict()))
